@extends('layouts.admin')
@section('pageTitle', '活动列表')
@section('style')
    <link href="//cdn.bootcss.com/bootstrap-daterangepicker/2.1.25/daterangepicker.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/CSS/main.css"/>
    <style>
        select[name=companyId]{
            height: 40px;
            line-height: 40px;
            border: 1px solid #E3E3E3;
            padding: 0 10px;
            border-radius: 4px;
            -webkit-border-radius: 4px;
        }
    </style>
    <script>
        var table_option = {
            search:false
        };
    </script>
    <script type="text/javascript" src="/js/admin/jquery-1.12.4.min.js"></script>
    <script type="text/javascript" src="/js/admin/angular.min.js"></script>
    <script type="text/javascript" src="/js/admin/angular-animate.min.js"></script>
    <script type="text/javascript" src="/js/admin/jquery.nicescroll.min.js"></script>
@endsection
@section('content')
    <script>
        tableAjaxParams['activity_id'] = '{{$activity_id}}';
        @if(!empty($activity))
                tableAjaxParams['start'] ='{{$activity->startTime}}';
                tableAjaxParams['end'] ='{{$activity->endTime}}';
        @endif
    </script>
    <div class="main-panel">
        <div class="content apartment-index" ng-controller="ActivityRecordsController">
            <div class="container-fluid" style="min-height:600px;">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="header">
                                <legend>中奖列表</legend>
                            </div>
                            <div class="toolbar">
                                <a class="btn btn-info btn-fill btn-wd pull-left" href="/web/activityRecords/export?activity_id={{$activity_id}}" >导出数据</a>
                                <div class="form-group pull-left mg20" >
                                    <input type="text" date-range-picker data-start="@{{search.start}}" data-end="@{{search.end}}" class="form-control">
                                </div>
                                <div class="form-group pull-left mg20" style="width: 240px;">
                                    <div class="input-group">
                                        <input type="text" class="form-control" ng-model="search.mobile"  placeholder="领奖手机号">
                                        <div class="input-group-addon pd0"><button class="btn input-btn pd0" ng-click="searchMobile()"><i class="glyphicon glyphicon-search"></i></button></div>
                                    </div>
                                </div>
                            </div>

                            <table id="bootstrap-table-container" class="table" data-url="/web/activityRecords/list" data-delete-url="/web/activity/delete">
                                <thead>
                                <th data-field="created_at" data-sortable="true">中奖时间</th>
                                <th data-field="openid"  data-sortable="false">中奖ID</th>
                                <th data-field="participant.nickname" data-formatter="participantNicknameFormatter" data-sortable="false">中奖人</th>
                                <th data-field="participant.mobile" data-formatter="participantMobileFormatter" data-sortable="false">手机号</th>
                                <th data-field="prize.name" data-formatter="prizeNameFormatter" data-sortable="false">奖品名称</th>
                                <th data-field="prize.type.name" data-formatter="prizeTypeFormatter" data-sortable="false">奖品类型</th>
                                <th data-field="is_exchange" data-formatter="statusFormatter" data-sortable="false">中奖状态</th>
                                <th data-field="coupon" data-formatter="couponFormatter" data-sortable="false">兑奖码</th>
                                <th data-field="actions" class="td-actions text-center" data-events="operateEvents" data-formatter="operateFormatter">操作</th>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div><!--  end card  -->
                    </div> <!-- end col-md-12 -->
                </div> <!-- end row -->
            </div>
        </div>
    </div>

@endsection

@section('script')
    <script>
        require(['angular','directives'],function(angular){
            var app = angular.module('app',['directives']);
            app.controller('ActivityRecordsController',['$scope','$http','$compile',function ($scope,$http,$compile) {
                $scope.search={
                    activity_id:'{{$activity_id}}',
                    start:'',
                    end:'',
                    mobile:''
                };
                @if(!empty($activity))
                        $scope.search['start'] = '{{$activity->startTime}}';
                        $scope.search['end'] = '{{$activity->endTime}}'
                @endif
                $scope.searchMobile = function () {
                    $('#bootstrap-table-container').bootstrapTable('refreshOptions',{
                        queryParams:function(params){
                            return $.extend(params,$scope.search);
                        }
                    });
                };
                $scope.$watch('search.activity_id', function(newValue, oldValue) {
                    console.log(1);
                    if (newValue !=oldValue){
                        $('#bootstrap-table-container').bootstrapTable('refreshOptions',{
                            queryParams:function(params){
                                return $.extend(params,$scope.search);
                            }
                        });
                        //$('#bootstrap-table-container').bootstrapTable('refresh');
                    }
                });
                $scope.$on('date-range-select',function (event,res) {
                    $scope.search['start'] =res.start.format('YYYY-MM-DD');
                    $scope.search['end'] = res.end.format('YYYY-MM-DD');
                    $('#bootstrap-table-container').bootstrapTable('refreshOptions',{
                        queryParams:function(params){
                            return $.extend(params,$scope.search);
                        }
                    })
                   // $('#bootstrap-table-container').bootstrapTable('refresh');
                })
                $('#bootstrap-table-container')[0].addEventListener('table-refresh',function(e){
                    $('#bootstrap-table-container').bootstrapTable('refreshOptions',{
                        queryParams:function(params){
                            return $.extend(params,$scope.search);
                        }
                    })
                });
            }]);
            angular.bootstrap(document,['app']);
        })
       var companies = [];
        $.ajax({
            method: 'GET',
            url: '/api/logistics/companies',
            dataType: 'json',
            contentType: "application/json",
        }).success(function(data){
            if(data.code==200){
                companies = data.data;
            }else{
                utils.showNotification(data.message,3);
            }
        }).error(function(data){
            utils.showNotification('网络异常，稍后重试!',4);
        });

        function duijiang(row,callback) {
            if(row.is_exchange==0&&row.prize.type_code=='entity'){
                var html = '<form class="row" id="convertModal">' +
                    '       <div class="input-group">' +
                    '           <label>快递公司</label>' +
                    '           <select name="companyId">';
                for(var i=0,l=companies.length;i<l;i++){
                    html += '<option value="'+companies[i].id+'">'+companies[i].name+'</option>';
                }
                 html += '           </select>'+
                    '       </div>'+
                    '       <div class="input-group">' +
                '            <label>运单编号</label>' +
                '            <input name="number" type="text" placeholder="请输入运单编号"/>' +
                '       </div>'
                '</form>';
                var entity_convert = utils.modal('兑奖',html,false,function (res){
                    if(res == 1){
                        var data = $("#convertModal").serialize();
                        var dataArr = data.split("&");
                        var jsonData = {};
                        for(var i=0;i<dataArr.length;i++){
                            var params = dataArr[i].split("=");
                            jsonData[params[0]] = decodeURIComponent(params[1]);
                        }
                        if(!jsonData.companyId){
                            utils.showNotification('请选择快递公司',3);
                            return false;
                        }
                        if(!jsonData.number){
                            utils.showNotification('请输入运单编号',3);
                            return false;
                        }
                        var postData = {
                            "record_id": row.id,   // 中奖纪录的id
                            "company_id": jsonData.companyId,  // 物流公司id, api/logistics/companies接口获得
                            "order_number": jsonData.number // 快递单号
                        };
                        $.ajax({
                            url: '/api/prize/logistics',
                            data: JSON.stringify(postData),
                            type: 'POST',
                            dataType: 'json',
                            contentType: "application/json; charset=utf-8",
                            success: function(data) {
                                if(data.code==200){
                                    entity_convert.modal('hide');
                                    $('#bootstrap-table-container').bootstrapTable('refresh');
                                }else{
                                    utils.showNotification(data.message,3);
                                }
                            }
                        });
                    }
                })
            }else{
                utils.showConfirm('是否设置为已兑奖状态？',{},function () {
                    $.isLoading({text:'兑奖提交中，请稍后。。。'});
                    $.post('/web/activityRecords/duijiang',{
                        id: row.id
                    },function (res) {
                        $.isLoading('hide');
                        if (res.code == 0){
                            utils.showNotification('兑奖成功',2);
                            var event = new CustomEvent("table-refresh", {});
                            $('#bootstrap-table-container')[0].dispatchEvent(event);
                            if (callback){
                                callback();
                            }
                        }else {
                            utils.showNotification(res.message,4);
                        }
                    });


                });
            }
        }

        window.operateEvents = {
            'click .duijiang':function (e,value,row) {
                duijiang(row);
            },
            'click .detail':function (e,value,row) {
                var options = ['返回'];
                if (row.is_exchange == 0){
                    options.push('兑奖');
                }
                var content = '<form class="form-horizontal">';
                    console.log(row['prize']['prize_type']['code']+'=='+(row['prize']['prize_type']['code'] == 'entity'));
                    if(row['prize']['prize_type']['code'] == 'entity'){
                        var logistics_order = "";
                        var logistics_company = "";

                        if (row.logistics) {
                            logistics_order = row.logistics.order_number;

                            if (row.logistics.company) {
                                logistics_company = row.logistics.company.name;
                            }
                        }

                        content += '<div class="form-group">' +
                            '<label class="col-sm-2 control-label">姓名</label>' +
                            '<div class="col-sm-10">' +
                            '<p class="form-control-static">'+row.name+'</p>' +
                            '</div>' +
                            '</div>'+
                            '<div class="form-group">' +
                            '<label class="col-sm-2 control-label">联系电话</label>' +
                            '<div class="col-sm-10">' +
                            '<p class="form-control-static">'+row.mobile+'</p>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-sm-2 control-label">地址</label>' +
                            '<div class="col-sm-10">' +
                            '<p class="form-control-static">'+row.address+'</p>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-sm-2 control-label">物流公司</label>' +
                            '<div class="col-sm-10">' +
                                '<p class="form-control-static">'+logistics_company+'</p>' +
                            '</div>' +
                            '</div>' +
                            '<div class="form-group">' +
                            '<label class="col-sm-2 control-label">运单编号</label>' +
                            '<div class="col-sm-10">' +
                            '<p class="form-control-static">'+logistics_order+'</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                    }
                    if(row['prize']['prize_type']['code'] == 'coupon'){
                        content += '<div class="form-group">' +
                            '          <label class="col-sm-2 control-label">兑奖方式</label>' +
                            '          <div class="col-sm-10">' +
                            '               <p class="form-control-static">' + (row.prize.exchange_method==0?"线上网址兑换":"线下门店兑换") + '</p>' +
                            '          </div>' +
                            '       </div>';
                        if(row.prize.exchange_method==1){
                            var extendsData
                            try{
                                extendsData = JSON.parse(row.extends);
                            }catch (e) {
                                extendsData = {};
                            }
                            Object.keys(extendsData).forEach(function (key) {
                                content += '<div class="form-group">' +
                                    '          <label class="col-sm-2 control-label">'+key+'</label>' +
                                    '          <div class="col-sm-10">' +
                                    '               <p class="form-control-static">' + extendsData[key] + '</p>' +
                                    '          </div>' +
                                    '       </div>';
                            })
                        }
                    }
                    content += '<div class="form-group">' +
                                '<label class="col-sm-2 control-label">中奖时间</label>' +
                                '<div class="col-sm-10">' +
                                '<p class="form-control-static">'+row.created_at+'</p>' +
                                '</div>' +
                                '</div>'+
                                '<div class="form-group">' +
                                '<label class="col-sm-2 control-label">奖品名称</label>' +
                                '<div class="col-sm-10">' +
                                '<p class="form-control-static">'+row['prize']['name']+'</p>' +
                                '</div>' +
                                '</div>'+
                                '<div class="form-group">' +
                                '<label class="col-sm-2 control-label">奖品类型</label>' +
                                '<div class="col-sm-10">' +
                                '<p class="form-control-static">'+row['prize']['prize_type']['name']+'</p>' +
                                '</div>' +
                                '</div>'+
                                '<div class="form-group">' +
                                '<label class="col-sm-2 control-label">中奖状态</label>' +
                                '<div class="col-sm-10">' +
                                '<p class="form-control-static">'+(row.is_exchange ==0?'未兑奖':'已兑奖')+'</p>' +
                                '</div>' +
                                '</div>'+
                                '<div class="form-group">' +
                                '<label class="col-sm-2 control-label">中奖卷码</label>' +
                                '<div class="col-sm-10">' +
                                '<p class="form-control-static">'+(row.coupon == ''?'--':row.coupon)+'</p>' +
                                '</div>' +
                                '</div>'+
                                '</form>';
                var detailDialog = utils.modal('中奖详情',content,options,function (res) {
                    if (res == 1 && row.is_exchange == 0){
                        duijiang(row,function () {
                            detailDialog.modal('hide');
                        });
                    }else {
                        detailDialog.modal('hide');
                    }

                });
            }
        };

        function participantNicknameFormatter(value,row) {
            if(row['participant']){
                return row['participant']['nickname'];
            }
            return '--';
        }

        function participantMobileFormatter(value,row) {
            if(row['participant'] && row['participant']['mobile']){
                return row['participant']['mobile'];
            }else{
                return '--';
            }
        }

        function prizeNameFormatter(value,row) {
            return row['prize']['name'];
        }

        function prizeTypeFormatter(value,row) {
            return row['prize']['prize_type']['name'];
        }

        function couponFormatter(value,row)
        {
            if(row['coupon']){
                return row['coupon'];
            }else{
                return '--';
            }
        }

        function statusFormatter(value,row) {
            var str = '';
            switch (value){
                case 0:
                    str = '<span class="text-danger">未兑奖</span>';
                    break;
                case  1:
                    str = '<span class="text-success">已兑奖</span>';
                    break;
            }
            return str;
        }
        function operateFormatter(value,row) {
            var actions = [];
            if(row.is_exchange == 0){
                actions.push('<a rel="tooltip" title="兑奖" class="btn btn-simple btn-warning btn-icon table-action duijiang" href="javascript:;"><i class="glyphicon glyphicon-tasks"></i></a>');
            }
            actions.push('<a rel="tooltip" title="查看详情" class="btn btn-simple btn-info btn-icon table-action detail" href="javascript:;"><i class="glyphicon glyphicon-eye-open"></i></a>')
            return actions.join('');
        }
        $('#bootstrap-table-container').on('post-body.bs.table',function () {
            $('[rel="tooltip"]').tooltip();

        });
    </script>


@endsection